package com.yihang.jdbcDemo.ftp.config;

import com.github.drapostolos.rdp4j.spi.FileElement;
import com.github.drapostolos.rdp4j.spi.PolledDirectory;
import com.yihang.jdbcDemo.ftp.core.FtpClientTemplate;
import com.yihang.jdbcDemo.utils.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.util.LinkedHashSet;
import java.util.Set;

/**
 * ftp获取文件地址
 */
@Slf4j
public class FtpDirectory implements PolledDirectory {


    FtpClientTemplate ftpClientTemplate = SpringUtil.getBean(FtpClientTemplate.class);
    FtpClientProperties ftpClientProperties = SpringUtil.getBean(FtpClientProperties.class);

    /**
     * 获取文件列表
     *
     * @return
     * @throws IOException
     */
    @Override
    public Set<FileElement> listFiles() throws IOException {
        FTPClient ftpClient = null;
        try {
            ftpClient = ftpClientTemplate.getFtpClientPool().borrowObject();
            int replyCode = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(replyCode)) {
                log.warn("ftpServer refused connection, replyCode:{}", replyCode);

            }
            //ftpClient.changeWorkingDirectory("/pull");
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            Set<FileElement> result = new LinkedHashSet<FileElement>();
            for (FTPFile file : ftpClient.listFiles(ftpClientProperties.getFtpPullPath())) {
                result.add(new FtpFile(file));
            }
            return result;


        } catch (Exception e) {
            throw new IOException(e);
        } finally {
            //将对象放回池中
            ftpClientTemplate.getFtpClientPool().returnObject(ftpClient);
        }


    }
}